package com.lock.type;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: tgy
 * @Date: 2020-07-31 14:11
 */

class MiddleData{

    private Lock lock01 = new ReentrantLock();
    private Lock lock02 = new ReentrantLock();


    public void run01(){


        lock01.lock();

        try {

            TimeUnit.SECONDS.sleep(2);

            lock02.lock();

            try {

                System.out.println("run01");

            }finally {

                lock02.unlock();
            }


        }catch (Exception e){

        }finally {

            lock01.unlock();
        }


    }

    public void run02(){


        lock02.lock();

        try {

            TimeUnit.SECONDS.sleep(2);

            lock01.lock();

            try {

                System.out.println("run02");

            }finally {

                lock01.unlock();
            }


        }catch (Exception e){

        }finally {

            lock02.unlock();
        }


    }
}

/**
 * 死锁检查
 *
 * 1. jps -l 列出运行的Java进程
 * 8363 org.jetbrains.idea.maven.server.RemoteMavenServer
 * 16188 org.jetbrains.jps.cmdline.Launcher
 * 9053 com.eureka.EurekaApplication
 * 16189 com.lock.type.DeadLockTest
 * 9086 com.order.OrderHystrixApplication
 * 16319 sun.tools.jps.Jps
 *
 * 2. jstack 16189 打印对应的进程运行栈
 */
public class DeadLockTest {



    public static void main(String[] args) {

        MiddleData middleData = new MiddleData();

        new Thread(()->{

                middleData.run01();
        }).start();

        new Thread(()->{

            middleData.run02();
        }).start();


    }
}
